package com.zzyl.job;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.vo.AlertRuleVo;
import com.zzyl.vo.DeviceDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class AlertJob {

    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private AlertRuleService alertRuleService;

    @Scheduled(cron = "0 * * * * ?")
    public void deviceDataAlertFilter() {
        // 获取所有规则
        List<AlertRuleVo> allAlertRules = alertRuleMapper.getAll();
        // 判断是否为空
        if(ObjectUtil.isEmpty(allAlertRules)){
            return;
        }

        // 查询所有设备上的数据
        List<String> deviceData =  new ArrayList<>();
        allAlertRules.forEach(allAlertRule -> {
            String s = redisTemplate.opsForValue().get("device:data" + allAlertRule.getIotId());
            if(ObjectUtil.isNotEmpty(s)){
                deviceData.add(s);
            }
        });
        // 判断是否为空
        if(ObjectUtil.isEmpty(deviceData)){
            return;
        }

        // 数据格式标准化处理
        List<DeviceDataVo> deviceDataVos = new ArrayList<>();
        deviceData.forEach(deviceDataStr -> {
            deviceDataVos.addAll(JSONUtil.toList(deviceDataStr, DeviceDataVo.class));
        });

        // 数据报警处理
        deviceDataVos.forEach(deviceDataVo -> {
           alertRuleService.alertFilter(deviceDataVo);
        });
    }
}
